<template>
  <div class="app-container">
    <comprehensive-table
            @selection-change="selectionChange"
            :columns="column" :data="data" @reset="reset" @onSubmit="onSubmit"  @custom-size-change="handleCustomSizeChange" @custom-select-change="handleCustomSelectChange">
      <template v-slot:btn>
       <div style="display: flex;justify-content: flex-end">
         <el-button type="primary" @click="add"><el-icon><plus /></el-icon> 添加</el-button>
         <el-button type="danger" @click="batchDelete"><el-icon><delete /></el-icon>批量删除</el-button>
       </div>
      </template>
      <template v-slot:sex="scope">{{scope.row.sex?'男':'女'}}</template>
      <template v-slot:operation="scope">
        <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="edit(scope.row)"
        >
          编辑
        </el-button>
        <el-button
             @click="del(scope.row)"
            type="danger"
            size="small"
            icon="Delete"
        >
          删除
        </el-button>
      </template>
    </comprehensive-table>

    <el-dialog
        :visible.sync="dialogVisible"
            :title="title"
            width="50%"
    >
      <el-form
              ref="ruleFormRef"
              :model="ruleForm"
              :rules="rules"
              label-width="120px"
              class="demo-ruleForm"
              :size="formSize"
      >
		<el-form-item label="站点名称" prop="name">
		  <el-input v-model="ruleForm.name" />
		</el-form-item>
		<el-form-item label="地址" prop="address">
		  <el-input v-model="ruleForm.address" />
		</el-form-item>
		<el-form-item label="联系电话" prop="phone">
		  <el-input v-model="ruleForm.phone" />
		</el-form-item>
		<!-- <el-form-item label="上传图片" prop="avatar">
		  <div v-if="uploadedImage">
		      <img :src="uploadedImage" alt="上传的图片">
		    </div>
		    <el-upload
		      class="upload-demo"
		      action="/upload"
		      :on-success="handleUploadSuccess"
		      :before-upload="beforeUpload"
		      :on-remove="handleRemove"
		      :auto-upload="false"
		    >
		      <el-button size="small" type="primary" class="upload-btn">点击上传</el-button>
		    </el-upload>
		  </el-upload>
		</el-form-item> -->
		 <el-form-item label="开门时间" prop="openTime">
	     <el-time-picker
	       v-model="ruleForm.openTime"
	       placeholder="选择开门时间"
	       format="HH:mm:00"
				:picker-options="pickerOptions"
	     ></el-time-picker>
	   </el-form-item>
    <el-form-item label="关门时间" prop="closeTime">
      <el-time-picker
        v-model="ruleForm.closeTime"
        placeholder="选择关门时间"
        format="HH:mm:00"
				:picker-options="pickerOptions"
      ></el-time-picker>
		      </el-form-item>
		<el-form-item label="经度-180~180" prop="lon">
		  <el-input-number v-model="ruleForm.lon" :min="-180" :max="180" :step="0.0001"></el-input-number>
		</el-form-item>
		<el-form-item label="纬度-90~90" prop="lat">
		  <el-input-number v-model="ruleForm.lat" :min="-90" :max="90" :step="0.0001"></el-input-number>
		</el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleClose('ruleFormRef')"
        >确定</el-button
        >
      </span>
      </template>
    </el-dialog>

  </div>
</template>
<script>
	
var dayjs = require('dayjs')
  import ComprehensiveTable from './components/comprehensive.vue'
	import axios from 'axios'
  const data = []
  
  
  const column = [
    { type:'selection', width:60 },
    { name:'id', label: 'id',valueType:'input',width:100, },
		{	name:'name', label: '站点名称',	inSearch:true,	valueType:'input',	width:140},
		{	name:'address', label: '地址',	valueType:'input',	width:140},
		{	name:'phone', label: '联系号码', valueType:'input',width:140},
		// {name:'images', label: '图片',width:130},
		{	name:'openTime', label: '开门时间',		valueType:'input',	width:100},
		{	name:'closeTime', label: '关门时间',		valueType:'input',	width:100},
		{	name:'lon', label: '站点经度',		valueType:'input',	width:100},
		{	name:'lat', label: '站点纬度',		valueType:'input',	width:100},
    { name: 'operation',slot:true,fixed:'right',width:200 }
  ]
  export default {
    components:{
      ComprehensiveTable
    },
    data(){
      return{
        data,
        column,
        formSize:'default',
        ruleForm:{
          id:null,
					name: '',
					address:null,
					phone:null,
					state:'',
					images:'',
					openTime: null,
					closeTime:null,
					lon:null,
					lat:null,
        },
				pickerOptions: {
				  start: '00:00',  // 可选时间范围的开始时间
				  end: '23:59',    // 可选时间范围的结束时间
				  step: '00:15'    // 时间的间隔单位设置为15分钟
				},
        rules:{
					phone:[
						{ required: true, message: '请输入联系电话', trigger: 'blur' },
						{ pattern: /^\d{11}$/, message: '手机号码必须为11位数字', trigger: 'blur' }
					],
					images: [
					  {  message: '请上传头像', trigger: 'change' }
					],
					name:[
						{ required: true, message: '请输入站点名字', trigger: 'blur' },
						{ min: 1, max: 9, message: '名称不能超过9位', trigger: 'blur' },
					],
					lon: [
					  { required: true, message: '请输入经度', trigger: 'change' },
					  { type: 'number', message: '请输入数字', trigger: 'change' },
					  { min: -180, max: 180, type: 'number', message: '请输入有效的经度', trigger: 'change' }
					],
					lat: [
					  { required: true, message: '请输入纬度', trigger: 'change' },
					  { type: 'number', message: '请输入数字', trigger: 'change' },
					  { min: -90, max: 90, type: 'number', message: '请输入有效的纬度', trigger: 'change' }
					],
					address:[
						{ required: true, message: '请输入地址', trigger: 'blur' },
						
					],
				},
        dialogVisible:false,
        title:'新增',
        rowObj:{},
        selectObj:[],
				uploadedImage: null,
				pageSize:10,
      }
    },
		created() {
		  this.fetchData();
		},
    methods:{
			fetchData() {
			  axios.get('http://43.136.172.73/api/v1/system/GbStation/selectAll/', {
					headers:{
						Authorization:''
					}
			  })
			  .then(response => {
			    this.data = response.data;
					console.log(response);
			  })
			  .catch(error => {
			    console.error('Error:', error);
			  });
			},
			validateNumberWith3Decimal(rule, value, callback) {
			  const numberRegex = /^\d+(\.\d{3})?$/;
			  if (!numberRegex.test(value)) {
			    callback(new Error('请输入3位小数的数字'));
			  } else {
			    callback();
			  }
			},
      async handleClose(formName){
				
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (valid) {
              let obj = {
                ...this.ruleForm,
              }
							
							obj.closeTime = this.ruleForm.closeTime;
							obj.openTime = this.ruleForm.openTime;
							// let closeTime = new Date(obj.closeTime);
							let formattedCloseTime = new Date(obj.closeTime).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
							let formattedopenTime = new Date(obj.openTime).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
							obj.closeTime = formattedCloseTime;
							obj.openTime = formattedopenTime;
							console.log(obj.openTime ,obj.closeTime);
              if(this.title==='新增'){
								axios.post('http://43.136.172.73/api/v1/system/GbStation/addNew/',{
										address:obj.address,
										closeTime:obj.closeTime,
										name:obj.name,
										openTime:obj.openTime,
										phone:obj.phone,
										lon:obj.lon,
										lat:obj.lat,
										images:obj.images
										
									},{
										headers:{
											Authorization:''
										},
									}).then(response => {
										console.log(response.data); // 处理响应结果
										this.$message.success('添加成功');
										this.fetchData();
									})
									.catch(error => {
										console.error(error); // 处理请求错误
										
									})
								
              }else {
                this.data.forEach(item=>{
                  if(item.id===this.rowObj.id){
                    item.address=obj.address
                    item.closeTime=obj.closeTime
                    item.name=obj.name
										item.openTime=obj.openTime
										item.phone=obj.phone
										item.lon=obj.lon
										item.lat=obj.lat
										item.images=obj.images
                  }
				    
                });
								console.log(obj);
								obj.closeTime = obj.closeTime.slice(0, -2) + '00';
								obj.openTime = obj.openTime.slice(0, -2) + '00';
								
								axios.put('http://43.136.172.73/api/v1/system/GbStation/update', {
										name: obj.address,
										closeTime: obj.closeTime,
										name:obj.name,
										id:obj.id,
										openTime:obj.openTime,
										phone:obj.phone,
										lon:obj.lon,
										lat:obj.lat,
									},{
										headers:{
											Authorization:''
										}
								})
								  .then(response => {
								    console.log(response);
										this.$message.success('修改成功')
										this.fetchData();
								  })
								  .catch(error => {
								    console.error(error);
								  })
								
              }
              this.dialogVisible = false
              // console.log('submit!',obj)
            } else {
              console.log('error submit!', fields)
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      add(){
        this.title='新增'
        this.dialogVisible = true
      },
      batchDelete(){
        if(!this.selectObj.length){
          return this.$message.error('未选中任何行')
        }
        this.$confirm(
            '你确定要删除选中项吗?',
            '温馨提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
              draggable: true,
            }
        )
            .then(() => {
              console.log(this.selectObj);
              const idArray = [];
              this.selectObj.map(item => (idArray.push(item.id)));
							const newArr = idArray.map(item => ({"id":item}));
              console.log(newArr);
              const url = 'http://43.136.172.73/api/v1/system/GbStation/deleteByList';
              	axios.post(url,newArr,{
										headers: {
              	    Authorization:'dsa' 
              	  },
              	}).then(response => {
                  // 处理成功响应
              		console.log(response);
              		this.$message.success('删除成功')
              		this.fetchData()
                })
                .catch(error => {
                  // 处理错误
                })
            })
            .catch(() => {

            })
      },
       selectionChange(val) {
		     console.log('选中项：', val);
		(val)=>emit('comprehensive',val)
         this.selectObj = val;
       },
      edit(row){
        this.title='编辑'
        this.rowObj = row
        this.dialogVisible = true
        this.ruleForm.name = row.name
				this.ruleForm.id = row.id
				this.ruleForm.phone = row.phone
		    this.ruleForm.address = row.address
        this.ruleForm.lon = row.lon
				this.ruleForm.lat = row.lat
				this.ruleForm.openTime = row.openTime
				this.ruleForm.closeTime = row.closeTime
				console.log(this.ruleForm);
      },
      del(row){
        this.$confirm(
            '你确定要删除当前项吗?',
            '温馨提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
              draggable: true,
            }
        )
            .then(() => {
             console.log(row.id);
             const url = 'http://43.136.172.73/api/v1/system/GbStation/delete/'+row.id;
             const headers = {Authorization:'dsa'}
             	axios.delete(url, {
             	  headers: {
             	    Authorization:'' 
             	  },
             	}).then(response => {
                 // 处理成功响应
             		console.log(response);
             		this.$message.success('删除成功')
             		this.fetchData()
               })
               .catch(error => {
                 // 处理错误
               })
            })
            .catch(() => {

            })
      },
      reset(){
        this.$message.success('触发重置方法')
				this.fetchData();
      },
      onSubmit(childData){
        this.$message.success('触发查询方法')
				console.log(childData);
				const obj = childData
				console.log(obj);
				axios.get('http://43.136.172.73/api/v1/system/GbStation/selectByName/'+obj.name, {
					headers:{
						Authorization:''
					}
				})
				.then(response => {
					console.log(response);
					this.data = response.data;
					this.$message.success('触发查询方法');
				})
				.catch(error => {
					console.error('Error:', error);
				});
								
      },
			handleCustomSizeChange(val){
				console.log(val);
				this.pageSize = val;
				console.log(this.pageSize);
				const totalPage = Math.ceil(this.totalItems / this.pageSize);
				// 处理当前页超出新的总页数的情况
				if (this.currentPage > totalPage) {
				  this.currentPage = totalPage;
				}
				
			},
			//左边选择中的id
			handleCustomSelectChange(val){
				console.log(val);
				this.selectObj = val;
			},
			handleUploadSuccess(response, file, fileList) {
			    // 假设上传成功后的图片URL在response中
			  this.uploadedImage = response.url;
				console.log(this.uploadedImage);
			},
    }
  }

</script>
<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
